/**
 * Created by Julia on 2016/4/28.
 */
define(['jquery', 'domReady!', 'appConst', 'appLocalStorage', 'model/global', 'model/role', 'business/role/roleConfig', 'appMessageBox', 'jquery-form/jquery-form.min'], function ($, domReady, appConst, appLocalStorage, global, roleM, roleConfig, msgBox) {
    var components = {};
    var data = {
        searchFields: {},
        search_key: appConst.searchKey.search_role_key + global.getUserId()
    };
    var that;
    return {
        init: function () {
            that = this;
            components = {
                fm_roleCreate: $("#fm_roleCreate"),
                txt_role_name: $("#txt_role_name"),
                txt_role_desc: $("#txt_role_desc"),
                txt_role_enabled: $("#txt_role_enabled"),
                btn_enabled: $('.r-enabled')
            };
            that.initCreateForm();
        },
        initCreateForm: function () {
            components.fm_roleCreate.validate({
                rules:roleConfig.rules,
                messages:roleConfig.messages,
                submitHandler: function (form) {
                    var searchParam = {
                        'name': components.txt_role_name.val(),
                        'description': components.txt_role_desc.val(),
                        'enabled':components.txt_role_enabled.val()
                    };
                    roleM.createRole(searchParam, function (d) {
                        data.searchFields.search_LIKE_name = components.txt_role_name.val();
                        appLocalStorage.setLocal(data.search_key, JSON.stringify(data.searchFields));
                        window.location.href = "#role";
                    }, function (msg) {
                        if (msg == "EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS") {
                            msgBox.errorBox(msg, components.txt_role_name.val());
                        } else {
                            msgBox.errorBox(msg);
                        }

                    });
                },
                errorPlacement:function (error,element) {
                    error.insertAfter(element.parent());
                }            });
        },
        initEvent: function () {
            components.btn_enabled.click(function(e) {
                components.btn_enabled.each(function (){
                    $(this).removeClass($(this).attr('data-enabled'));
                });
                $(this).addClass($(this).attr('data-enabled'));
                components.txt_role_enabled.val($(this).attr('data-value'));
            });
            components.btn_enabled.first().click();
           /* $('#lk_addnew').click(function(e){
                components.fm_roleCreate.removeClass('submited');
                components.fm_roleCreate[0].reset();
                e.preventDefault();
            });*/
        }
    }
});

